﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Globalization;
using SiteECSWeb;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;

/// <summary>
/// Summary description for PageBase
/// </summary>

namespace SiteECSWeb
{
    public class PageBase : Page
    {

        #region RefeshDetect

        public const string RefreshTicketCounter = "RefreshTicketCounter";

        public bool IsPageRefresh
        {
            get
            {
                object o = HttpContext.Current.Items[RefreshAction.PageRefreshEntry];
                if (o == null)
                    return false;
                return (bool)o;
            }
        }

        // Increase the internal counter used to generate refresh tickets
        public void TrackRefreshState()
        {
            InitRefreshState();
            int ticket = Convert.ToInt32(Session[RefreshTicketCounter]) + 1;
            Session[RefreshTicketCounter] = ticket;
        }
        // Create the hidden field to store the current request ticket
        private void SaveRefreshState()
        {
            int ticket = Convert.ToInt32(Session[RefreshTicketCounter]) + 1;
            RegisterHiddenField(RefreshAction.CurrentRefreshTicketEntry, ticket.ToString());
        }

        // Ensure that the ticket counter is initialized
        private void InitRefreshState()
        {
            if (Session[RefreshTicketCounter] == null)
                Session[RefreshTicketCounter] = 0;
        }
        #endregion

        #region PageEventHandler
      
        protected override void OnPreInit(EventArgs e)
        {
            Page.Theme = Helper.GetThemes("SiteTheme");
            //this.Error += new EventHandler(PageBase_Error);            
            
            //HttpContext.Current.Request.Browser.Adapters;
                //Adapters["System.Web.UI.WebControls.GridView, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"]
           //= "SiteECSWeb.GridViewAdapterReset";
            
            base.OnPreInit(e);
        }
      
        void PageBase_Error(object sender, EventArgs e)
        {
            //throw new Exception("The method or operation is not implemented.");
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            //Page.Title = "التمثيل التجاى المصرى";
            SetPageTitle();
            //Page.SmartNavigation = true;
        }
        protected override void OnInit(EventArgs e)
        {

            if (User.Identity.IsAuthenticated)
            {
                //Response.Write(Membership.GetUser().UserName);
                if (Session["UserApproveStatus"] == null)
                {
                    if (Membership.GetUser().IsApproved)
                    {
                        Session["UserApproveStatus"] = Membership.GetUser().IsApproved;
                    }
                }
            }
            //if (this.MeasureExecutionTime)
            //{
            //    watch = new Stopwatch();
            //    watch.Start();
            //    this.RecordTimestamp("page execution starting.....");
            //}
            base.OnInit(e);
        }
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            SaveRefreshState();
        }
        protected override void OnPreRenderComplete(EventArgs e)
        {
            base.OnPreRenderComplete(e);

            ////postponed for something special

            //if (this.MeasureExecutionTime)
            //{
            //    this.RecordTimestamp("Page execution complete...");

            //    watch.Stop();

            //    Control addExecutionTo = this.Form;
            //    if (addExecutionTo == null)
            //        addExecutionTo = this;

            //    addExecutionTo.Controls.Add(new LiteralControl("<br /><br />"));

            //    StringBuilder timestampsOutput = new StringBuilder(50 * this.ExecutionTimestamps.Count);
            //    for (int i = 0; i < this.ExecutionTimestamps.Count; i++)
            //        timestampsOutput.AppendFormat("<b>Timestamp {0}</b>: {1:N0} ms ({2})<br />{3}",
            //                                        i + 1, this.ExecutionTimestamps[i].Timestamp,
            //                                        this.ExecutionTimestamps[i].Description, Environment.NewLine);

            //    addExecutionTo.Controls.Add(new LiteralControl(timestampsOutput.ToString()));
            //}
        }

        protected override void OnInitComplete(EventArgs e)
        {
            #region Firefox Fix
            ScriptManager sm = ScriptManager.GetCurrent(this);
            if (IsPostBack && Request.Browser.Browser == "Firefox" && sm != null 
                && sm.IsInAsyncPostBack == false && Request.Form["X-MicrosoftAjax"] == "Delta=true")
            {
                sm.GetType().GetField("_isInAsyncPostBack", System.Reflection.BindingFlags.NonPublic |
                    System.Reflection.BindingFlags.Instance).SetValue(sm, true);
            }
            #endregion
            base.OnInitComplete(e);
        }
        #endregion

        #region PathApplication&domainName
        protected virtual string BaseUrl
        {
            get
            {
                string url = this.Request.ApplicationPath;
                if (url.EndsWith("/"))
                    return url;
                else
                    return url + "/";
            }
        }

        protected virtual string FullBaseUrl
        {
            get
            {
                return this.Request.Url.AbsoluteUri.Replace(
                   this.Request.Url.PathAndQuery, "") + this.BaseUrl;
            }
        }

        protected virtual string DomianName
        {
            get
            {
                return "http://www.ecs.gov.eg/";
            }
        }

        protected virtual void RequestLoginUrl()
        {
            this.Response.Redirect(FormsAuthentication.LoginUrl +
               "?ReturnUrl=" + this.Request.Url.PathAndQuery);
        }

        #endregion

        #region SetPageTitle

        protected virtual bool AutoSetPageTitle
        {
            get
            {
                object o = ViewState["AutoSetPageTitle"];
                if (o == null)
                {
                    return true;
                }
                else
                {
                    return (bool)o;
                }
            }
            set
            {
                ViewState["AutoSetPageTitle"] = value;
            }
        }
        protected virtual string SiteMapNodeProvider
        {
            get
            {
                string  str = ViewState["SiteMapNodeProvider"] as string;
                if (str == null)
                {
                    return SiteMapProviderNames.BMenuXmlSiteMapProvider.ToString();
                }
                else
                {
                    return str;
                }
            }
            set
            {
                ViewState["SiteMapNodeProvider"] = value;
            }
        }
        protected virtual string SiteMapNodeSeparator
        {
            get
            {
                string str = ViewState["SiteMapNodeSeparator"] as string;
                if (str == null)
                    return " :: ";
                else
                    return str;
            }
            set
            {
                ViewState["SiteMapNodeSeparator"] = value;
            }
        }
        protected virtual void SetPageTitle()
        {
            if (this.AutoSetPageTitle && (string.IsNullOrEmpty(this.Title) ||
                string.Compare(this.Title, "Untitled Page", true) == 0))
            {
                if (SiteMap.Enabled)
                {
                    SiteMapNode current = null;
                    if (string.IsNullOrEmpty(this.SiteMapNodeProvider.ToString()))
                    {
                        current = SiteMap.RootNode;
                    }
                    else
                    {
                        current = SiteMap.Providers[this.SiteMapNodeProvider.ToString()].CurrentNode;
                    }
                    if (current != null)
                    {
                        SetPageTitle(current);
                        return;
                    }
                }
                this.Title = Path.GetFileNameWithoutExtension(Request.PhysicalPath);
            }
        }
        protected virtual void SetPageTitle(SiteMapNode current)
        {
            if (this.AutoSetPageTitle)
            {
                StringBuilder titleBuilder = new StringBuilder(200);
                //titleBuilder.Append(current.Title);
                //current = current.ParentNode;
                if (current != null)
                {
                    //string parentPathReserve = current.Title;
                    //while (current.ParentNode != null)
                    //{
                    //    current = current.ParentNode;
                    //    parentPathReserve = 
                    //        string.Concat(current.Title, this.SiteMapNodeSeparator, parentPathReserve);
                    //}
                    titleBuilder.Append("التمثيل التجارى المصرى -");
                    titleBuilder.Append(current.Title);
                }
                this.Title = titleBuilder.ToString();
            }
        }
        #endregion

        #region SetCultureInfo
        protected override void InitializeCulture()
        {
            string currentCulture = (HttpContext.Current.Profile as ProfileCommon).Culture;
            this.Culture = currentCulture;
            this.UICulture = currentCulture;
        }
        private CultureInfo _datetimeFormated = null;
        private CultureInfo _numberFormated = null;
        private CultureInfo _currentCultureInfo = null;
        protected virtual CultureInfo DateTimeFormated
        {
            get
            {
                if (_currentCultureInfo == null)
                {
                    _currentCultureInfo = CultureInfo.CurrentCulture;
                }
                _datetimeFormated = new CultureInfo(_currentCultureInfo.Name);
                DateTimeFormatInfo formates = _datetimeFormated.DateTimeFormat;
                formates.DateSeparator = "--";
                formates.ShortDatePattern = "dd/MM/yyyy";

                //formates.f
                return _datetimeFormated;
            }
        }
        protected virtual CultureInfo NumberFormated
        {
            get
            {
                if (_currentCultureInfo == null)
                {
                    _currentCultureInfo = CultureInfo.CurrentCulture;
                }
                _numberFormated = new CultureInfo(_currentCultureInfo.Name);
                NumberFormatInfo formates = _numberFormated.NumberFormat;
                //formates.= "-";
                //formates.ShortDatePattern = "dd/MM/yyyy";
                return _numberFormated;
            }
        }


        #endregion

        #region DisplayJavaScriptMessage
        public virtual void DisplayAlert(string message)
        {
            if (!ClientScript.IsStartupScriptRegistered(this.GetType(), "loginError"))
            {
                ClientScript.RegisterStartupScript(this.GetType(),
                    "loginError", string.Format("alert('{0}');", message.Replace("'", @"\'")), true);
            }
            //if (!ClientScript.IsOnSubmitStatementRegistered(this.GetType(),"loginError"))
            //{
            //    ClientScript.RegisterOnSubmitStatement(this.GetType(),
            //        "loginError", string.Format("alert('{0}');", message.Replace("'", @"\'")));
            //}
        }
        #endregion

        #region RecursiveFindControl

        protected virtual Control FindControlRecursive(string ControlID)
        {
            return FindControlRecursive(ControlID, this);
        }
        protected virtual Control FindControlRecursive(string ControlID, Control parent)
        {
            if (string.Compare(parent.ID, ControlID, true) == 0)
            {
                return parent;
            }
            foreach (Control child in parent.Controls)
            {
                Control match = FindControlRecursive(ControlID, child);

                if (match != null)
                {
                    return match;
                }
            }
            return null;
        }

        #endregion

        #region ExecutionTime_forPage

        private Stopwatch watch = null;
        private List<TimestampInfo> timestamps = null;

        protected virtual bool MeasureExecutionTime
        {
            get
            {
                object o = ViewState["MeasureExecutionTime"];
                if (o == null)
                {
                    return false;
                }
                else
                {
                    return (bool)o;
                }
            }
            set
            {
                ViewState["MeasureExecutionTime"] = value;
            }
        }
        protected virtual List<TimestampInfo> ExecutionTimestamps
        {
            get
            {
                if (timestamps == null)
                {
                    timestamps = new List<TimestampInfo>();
                }
                return timestamps;
            }
        }
        protected virtual void RecordTimestamp(string description)
        {
            if (watch == null)
            {
                throw new ArgumentException("you can't use it right now");
            }
            ExecutionTimestamps.Add(new TimestampInfo(watch.ElapsedMilliseconds, description));
        }

        #endregion
        
        #region CheckVaildForSubmissionControl
        protected override bool OnBubbleEvent(object source, EventArgs args)
        {
            //IButtonControl c = source as IButtonControl;
            //if (c != null && c.CausesValidation)
            //{
            //    Page.Validate();
            //    if (!Page.IsValid)
            //    {
            //        return false;
            //    }
            //}
            return base.OnBubbleEvent(source, args);
        }
        #endregion

        #region ActivityUserLog

        protected void LogActivity(string tableName,string columnName, 
            ActivityOperation actOperation, object oldValue, object newValue,
            string activityDescp, bool recordPageUrl)
        {
            if (Request.IsAuthenticated)
            {
                MembershipUser currentUser = Membership.GetUser(false);
                Guid userId = (Guid)currentUser.ProviderUserKey;
                //DBNull.Value
                using (SqlConnection myConn = 
                    new SqlConnection
                    (ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString))
                {
                    SqlCommand myCommand = new SqlCommand();
                    myCommand.CommandType = System.Data.CommandType.StoredProcedure;
                    myCommand.CommandText = "usp_LogUserActivity";
                    
                    myCommand.Connection = myConn;
                    myCommand.Parameters.AddWithValue("@UserId", userId);
                    myCommand.Parameters.AddWithValue("@TableName", tableName);
                    myCommand.Parameters.AddWithValue("@ColumnName", columnName);
                    myCommand.Parameters.AddWithValue("@ActivityOperation", actOperation.ToString());
                    if (actOperation == ActivityOperation.Inserted)
                    {
                        myCommand.Parameters.AddWithValue("@OldValue", DBNull.Value);
                    }
                    else
                    {
                        myCommand.Parameters.AddWithValue("@OldValue", oldValue);
                    }

                    myCommand.Parameters.AddWithValue("@NewValue", newValue);
                    myCommand.Parameters.AddWithValue("@ActivityDescription", activityDescp);
                    

                    if (recordPageUrl)
                    {
                        myCommand.Parameters.AddWithValue("@PageUrl",Request.RawUrl);
                    }
                    else
                    {
                        myCommand.Parameters.AddWithValue("@PageUrl", DBNull.Value);
                    }

                    myConn.Open();
                    myCommand.ExecuteNonQuery();
                    myConn.Close();
                }
            }
        }
        #endregion

        #region CheckECSEmpCurrentlyAndManageControl
        protected virtual string GetEcsEmpEditLink(object userNameOrEmail)
        {
            string url = string.Empty;
            if (userNameOrEmail != null)
            {
                string userName = Membership.GetUserNameByEmail(userNameOrEmail.ToString());

                if (!string.IsNullOrEmpty(userName))
                {
                    url =
                    Helper.NavURLParamsStringVirtualName(userName,
                    Globals.Settings.VirtualNamesInfo.EmployeeAccountEdit);
                }
                else
                {
                    url =
                        Helper.NavURLParamsStringVirtualName(userNameOrEmail.ToString(),
                        Globals.Settings.VirtualNamesInfo.EmployeeAccountEdit);
                }

            }
            return url;
        }
        protected virtual bool ApplyManageForAuthonticatedUser(string userName,             
            params RolesName[] rolesName )
        {
            bool userFlag = false;
            if (Page.User.Identity.IsAuthenticated)
            {
                if (!string.IsNullOrEmpty(userName))
                {
                    foreach (RolesName rolename in rolesName)
                    {
                        if (Roles.IsUserInRole(userName, rolename.ToString()))
                        {
                            userFlag = true;
                            break;
                        }
                        //if (rolename == RolesName.SysAdmin ||
                        //    rolename == RolesName.AdminSystem )
                        //{
                            
                        //}
                    }
                }
            }
            return userFlag;
        }
        protected virtual bool CheckEcsEmp(string userName, string Email)
        {
            bool userFlag = false;

            if (Page.User.Identity.IsAuthenticated)
            {
                if (string.IsNullOrEmpty(userName) &&
                    string.IsNullOrEmpty(Email))
                {
                    return userFlag;
                }
                if (!string.IsNullOrEmpty(Email))
                {
                    MembershipUser mUser = Membership.GetUser(userName);
                    if (string.Compare(mUser.Email, Email) == 0)
                    {
                        userFlag = true;
                    }
                }
            }
           
            return userFlag;
        }

        #endregion

        #region ViewStateCompress

        public const string VIEWSTATE_KEY_PREFIX = "VIEWSTATE#";
        public const string VIEWSTATE_KEY_FIELD_NAME = "__VIEWSTATE_KEY";
        public const string VIEWSTATE_INVALID_ERR_MSG = "Invalid viewstate key: ";

        protected override void SavePageStateToPersistenceMedium(object state)
        {
            string vsKey = VIEWSTATE_KEY_PREFIX + "_" + System.Guid.NewGuid();            
            LosFormatter formatter = new LosFormatter();
            StringWriter stateWriter = new StringWriter();
            formatter.Serialize(stateWriter, state);
            Session[vsKey] = stateWriter.ToString();
            RegisterHiddenField(VIEWSTATE_KEY_FIELD_NAME, vsKey);
        }
        protected override object LoadPageStateFromPersistenceMedium()
        {
            string vsKey = Request.Form[VIEWSTATE_KEY_FIELD_NAME];
            if (!vsKey.StartsWith(VIEWSTATE_KEY_PREFIX))
            {
                throw new System.Exception(VIEWSTATE_INVALID_ERR_MSG + vsKey);
            }
            LosFormatter formatter = new LosFormatter();
            object oSessionValue = Session[vsKey];
            object oViewState = null;
            if (oSessionValue != null)
            {
                oViewState = formatter.Deserialize((string)oSessionValue);
            }
            return oViewState;
        }
        #endregion
      
    }
}